package com.github.xzb617.security.perms;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xzb617.constant.SuperAdminConstant;
import com.github.xzb617.domain.common.ErrorResponse;
import com.github.xzb617.domain.common.ErrorStatus;
import com.github.xzb617.security.Subject;
import com.github.xzb617.security.SubjectHolder;
import com.github.xzb617.utils.AnnotationUtil;
import com.github.xzb617.utils.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限校验拦截器
 * @author xzb617
 */
@Component
public class PermsInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper;

    public PermsInterceptor(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取上下文的 Subject
        Subject subject = SubjectHolder.getContext();
        if (subject != null) {
            // 非匿名访问，判断是否需要进行权限校验
            CheckRole checkRole = AnnotationUtil.getMethodAnnotation(handler, CheckRole.class);
            if (checkRole != null) {
                // 接口上有该注解，进行权限校验
                Role cRole = checkRole.role();
                String role = subject.getRole();
                if (!cRole.getValue().equals(role)) {
                    // 权限不足
                    ResponseUtil.writeJSON(response, HttpStatus.FORBIDDEN, getNoPermJson());
                    return false;
                }
            }
        }

        // 放行
        return true;
    }


    protected String getNoPermJson() throws JsonProcessingException {
        return this.objectMapper.writeValueAsString(new ErrorResponse(ErrorStatus.INSUFFICIENT_ACCESS_AUTHORITY));
    }

}
